package cn.cheniy.swiftmark.common.feign;

import cn.hutool.core.util.StrUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**

 * 这个拦截器是 Feign 客户端层面的拦截。它会在 Feign 客户端发起 HTTP 请求之前对请求进行拦截和处理，
 * 用于添加认证相关的请求头信息，从而实现内部请求的校验和传递外部请求的认证信息，
 * 影响的是 Feign 客户端与服务端之间的请求交互过程。
 *
 * @author cheniy
 * @description 对 Feign 请求进行拦截和处理。
 *  
 */
@Component
@ConditionalOnClass ({RequestInterceptor.class})
public class FeignBasicAuthRequestInterceptor implements RequestInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(FeignBasicAuthRequestInterceptor.class);

    @Autowired
    private FeignInsideAuthConfig feignInsideAuthConfig;

    @Override
    public void apply(RequestTemplate template) {
        // feign的内部请求，往请求头放入key 和 secret进行校验
        template.header(feignInsideAuthConfig.getKey(), feignInsideAuthConfig.getSecret());

        // 获取请求信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if (attributes == null) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        // 获取外部请求的Authorization的值
        String authorization = request.getHeader("Authorization");

        // 为内部的请求添加上
        if (StrUtil.isNotBlank(authorization)) {
            template.header("Authorization", authorization);
        }
    }
}
